import { h } from 'vue';

import QFormCreate from '@/components/q-form-create/index.vue';
import { FormCreateItem } from '@/types/form-create';
import { cloneDeep } from 'lodash-es';
import { ModalOptions, NButton, useModal } from 'naive-ui';

type UseUpsetProps<P, D> = {
	formItems: FormCreateItem[];
	title?: string;
	api: (data: P) => Promise<D>;
	success?: (data: D) => void;
	modalOptions?: ModalOptions;
	slots?: Record<string, typeof h>;
	beforeOpen?: () => Promise<void>;
};

export const useUpset = <P, D>(params: UseUpsetProps<P, D>) => {
	const createFormRef = ref<InstanceType<typeof QFormCreate>>();
	const { modal, message } = useFeedback(['modal', 'message']);
	// const modal = useModal()
	// const message = useMessage()



	const loading = ref(false);

	const formItems = ref<FormCreateItem[]>(cloneDeep(params.formItems));

	const setFormItem = ({ field, value }: { field: string; value: Partial<FormCreateItem> }) => {
		const index = formItems.value.findIndex((item) => item.field === field);
		if (index !== -1) {
			formItems.value[index] = {
				...formItems.value[index],
				...(value as any),
			};
		}
	};

	const removeFormItem = (field: string) => {
		const index = formItems.value.findIndex((item) => item.field === field);
		if (index !== -1) {
			formItems.value.splice(index, 1);
		}
	};

	const showUpsetModal = async (options: ModalOptions & { initialData?: any }) => {
		const handleSubmit = async (data: P) => {
			loading.value = true;
			try {
				const res = await params.api(data);
				params.success?.(res);
				hide();
			} catch (error: any) {
				console.error(error);
				message.error(error.message);
			} finally {
				loading.value = false;
			}
		};

		const hide = () => {
			modalInstance.destroy();
		};

		const formCreate = defineComponent({
			setup() {
				onMounted(() => {
					createFormRef.value?.setValues(options.initialData ?? {}, 'merge');
				});

				return () =>
					h(
						QFormCreate,
						{
							labelWidth: 100,
							items: formItems.value as FormCreateItem[],
							ref: createFormRef,
							initialData: options.initialData,
						},
						params.slots
					);
			},
		});

		if (params.beforeOpen) {
			await params.beforeOpen();
		}

		const modalInstance = modal.create({
			preset: 'card',
			maskClosable: false,
			draggable: true,
			onAfterLeave() {
				formItems.value = cloneDeep(params.formItems);
				createFormRef.value?.reset();
			},
			content: () => h(formCreate),
			footer: () =>
				h('div', { class: 'flex justify-end gap-4' }, [
					h(
						NButton,
						{
							onClick: hide,
						},
						() => '取消'
					),
					h(
						NButton,
						{
							type: 'primary',
							loading: loading.value,
							disabled: loading.value,
							onClick: () => {
								createFormRef.value?.validate((error) => {
									if (!error) {
										handleSubmit(createFormRef.value?.getValues() as P);
									}
								});
							},
						},
						() => '确认'
					),
				]),
			...params.modalOptions,
			...options,
		});
	};

	const handleEdit = (options: ModalOptions & { initialData?: Partial<P> }) => {
		showUpsetModal({
			title: `编辑${params.title}`,
			initialData: options.initialData,
			...options,
		});
	};

	const handleAdd = (options?: ModalOptions & { initialData?: Partial<P> }) => {
		showUpsetModal({
			title: `新增${params.title}`,
			initialData: options?.initialData,
			...options,
		});
	};

	return {
		formItems,
		setFormItem,
		showUpsetModal,
		handleEdit,
		handleAdd,
		removeFormItem,
	};
};
